package blog

import (
	"dustbe/controller/password"
	"dustbe/database"
	"fmt"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
)

type CreatePackage struct {
	Password string `json:"password"`
	Name string `json:"name"`
	Tags string `json:"tags"`
	AdjustTime string `json:"adjustTime"`
	ImgUrl string `json:"imgUrl"`
	Text string `json:"text"`
}

func CreateBlog(c *gin.Context) {
	var createPackage CreatePackage
	err := c.ShouldBindJSON(&createPackage)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"data" : "请求体不正确"})
		return
	}

	createPassword := createPackage.Password
	if createPassword != password.MyPasswords.CreateBlog {
		c.JSON(http.StatusOK, gin.H{"code" : 4001, "data" : "密码错误（create）"})
		return
	}
	
	name := createPackage.Name
	tags := createPackage.Tags
	adjustTime := createPackage.AdjustTime
	imgUrl := createPackage.ImgUrl
	text := createPackage.Text

	fmt.Println(createPackage)

	index, err := database.GetBlogCurrentIndex()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code" : 4001, "data" : "获取最新博客索引失败"})
		fmt.Println(err.Error())
		return
	}

	_, err = database.CreateBlog(name, tags, adjustTime, imgUrl, index)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code" : 4001, "data" : "创建博客失败"})
		fmt.Println(err.Error())
		return
	}

	// 将文章输出到本地
	markdownFilePath := fmt.Sprintf("%s/%d.md", blogRoot, index)

	// 索引自增
	index = index + 1
	go func ()  {
		database.SetBlogCurrentIndex(index)	
	}()


	dstFile, err := os.Create(markdownFilePath)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer dstFile.Close()
	_, err = dstFile.WriteString(text)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code" : 4001, "data" : "markdown写入本地文件出错"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code" : 200, "data" : "创建博客成功"})
}